#!/bin/bash
# 
# File: stop-autossh.sh
# Purpose: stop autossh for tunnel sites
#

cd $(dirname "$0")
. ./common.sh

INSTALLDIR=$(cd "$(dirname "$0")"; pwd);
KILL_PORT_SCRIPT=$INSTALLDIR/kill-port.sh
KILL_AUTOSSH_SELF_SCRIPT=$INSTALLDIR/kill-autossh-self.sh

test "$1" && tunnelsites="$@" || tunnelsites=$(./sites.sh)

for tunnelsite in $tunnelsites; do
	tunnel_name=`echo ${tunnelsite} | cut -d = -f 1`;
	tunnel_port=`echo ${tunnelsite} | cut -d = -f 2 | cut -d _ -f 2 | cut -d : -f 1`;
	
	if [ -n "$tunnel_port" ] ; then
		if test -x $KILL_PORT_SCRIPT; then
			$KILL_PORT_SCRIPT $tunnel_port
			if [ $? -eq 0 ]; then
				info '['$tunnel_name'] ssh tunnel stop';
			else
				warn '['$tunnel_name'] ssh tunnel stop failed';
			fi				
		else
			warn '['$KILL_PORT_SCRIPT'] not exist';
			exit 1
		fi
		
		if test -x $KILL_AUTOSSH_SELF_SCRIPT; then
			$KILL_AUTOSSH_SELF_SCRIPT $tunnel_port
			if [ $? -eq 0 ]; then
				info '['$tunnel_name'] autossh self stop';
			else
				warn '['$tunnel_name'] autossh self stop failed';
			fi		
		else
			warn '['$KILL_AUTOSSH_SELF_SCRIPT'] not exist';
			exit 1
		fi
	else
		warn '['$tunnelsite'] ssh tunnel not found';
	fi
done
	




